package com.jhgk.jhcee.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhgk.jhcee.common.exception.ParamException;
import com.jhgk.jhcee.data.auth.entity.SysUserRoleRelation;
import com.jhgk.jhcee.data.auth.mapper.SysUserRoleRelationMapper;
import com.jhgk.jhcee.system.enums.SystemResultEnum;
import com.jhgk.jhcee.system.service.SysUserRoleRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @Author: lemon_xzp
 * @Date: 2021/9/30 22:11
 */
@Service(value = "SysUserRoleRelationServiceImpl")
public class SysUserRoleRelationServiceImpl extends ServiceImpl<SysUserRoleRelationMapper, SysUserRoleRelation> implements SysUserRoleRelationService {

    @Autowired
    SysUserRoleRelationMapper sysUserRoleRelationMapper;

    @Override
    public Boolean updateByUserId(Long userId, Long roleId) {
        if (null == userId || null == roleId) {
            throw new ParamException(SystemResultEnum.UPDATE_USER_ROLE_PARAM_NULL);
        }
        QueryWrapper<SysUserRoleRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        SysUserRoleRelation sysUserRoleRelation = sysUserRoleRelationMapper.selectOne(wrapper);
        if (null == sysUserRoleRelation){
            throw new ParamException(SystemResultEnum.NOT_FOUND);
        }
        sysUserRoleRelation.setRoleId(roleId);
        return this.update(sysUserRoleRelation, wrapper);
    }

    @Override
    public Integer updateByRoleId(Long roleId, List<Long> userId) {
        if (null == roleId || userId.isEmpty()) {
            throw new ParamException(SystemResultEnum.UPDATE_ROLE_USER_PARAM_NULL);
        }
        return Math.toIntExact(userId.stream().filter(uid -> this.saveByUserId(uid, roleId)).count());
    }

    @Override
    public Boolean saveByUserId(Long userId, Long roleId) {
        if (null == userId || null == roleId) {
            throw new ParamException(SystemResultEnum.UPDATE_USER_ROLE_PARAM_NULL);
        }
        // 查询
        QueryWrapper<SysUserRoleRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        SysUserRoleRelation sysUserRoleRelation = sysUserRoleRelationMapper.selectOne(wrapper);
        if (null == sysUserRoleRelation) {
            sysUserRoleRelation = new SysUserRoleRelation();
            sysUserRoleRelation.setRoleId(roleId);
            sysUserRoleRelation.setUserId(userId);
            return this.save(sysUserRoleRelation);
        }
        return this.updateByUserId(userId,roleId);
    }
}
